-- UIQCAccountRegister
-- Created by chengb Sep/7/2016
-- 青瓷账号注册界面

UIQCAccountRegister = class("UIQCAccountRegister", function()
    return cc.Layer:create();
end)

function UIQCAccountRegister.create()
    return UIQCAccountRegister.new();
end

local MIN_ACCOUNT_LEN  = 6;   -- 账号最小长度
local MAX_ACCOUNT_LEN  = 32;  -- 账号最大长度
local MIN_PASSWORD_LEN = 6;   -- 密码最小长度
local MAX_PASSWORD_LEN = 16;  -- 密码最大长度
local TIME_OUT_LIMIT   = 30;  -- 注册超时时间

-- 构造函数
function UIQCAccountRegister:ctor()
    self:setName("UIQCAccountRegister");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/login/QCAccountRegister.csb");
    self:addChild(node);
    self.node = node;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIQCAccountRegister:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIQCAccountRegister:registerEventCallback()
    -- 关注青瓷平台账号注册结果
    EventMgr.register("UIQCAccountRegister", event.QC_REGISTER_RESULT, function(args)
        local result  = args.result;
        local account = args.account;
        local msg     = args.msg;
        local errcode = args.errcode;

        closeCommunicatingForm();

        if result == "ok" then
            -- 成功
            alert(getLocStr("account_register_ok"));
        elseif type(msg) == "string" then
            alert(msg);
        else
            alert(getLocStr("account_register_fail"));
        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enter" then
            -- 显示登录界面的遮罩
            local uiLogin = UIMgr.getCurrentScene():getFormByName("UILogin");
            uiLogin:setMaskVisible(true);

        elseif ev == "exit" then
            -- 反注册所有事件
            EventMgr.removeAll("UIQCAccountRegister");

            -- 隐藏登录界面的遮罩
            local uiLogin = UIMgr.getCurrentScene():getFormByName("UILogin");
            if uiLogin then
                uiLogin:setMaskVisible(false);
            end
        end
    end);
end

-- 重绘
function UIQCAccountRegister:redraw()
    -- 标题
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_BROWN);
    titleLabel:setString(getLocStr("register_account"));

    local CT = findChildByName(self.node, "CT");

    -- 输入账号
    local accountInput = findChildByName(CT, "account_node/input_account");
    local editBoxSize = accountInput:getContentSize();
    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setAnchorPoint(cc.p(0, 0.5));
    editBox:setPosition(accountInput:getPosition());
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder(getLocStr("input_account"));
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_GRAY2);
    editBox:setFontColor(TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    editBox:setMaxLength(MAX_ACCOUNT_LEN);
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE);
    self.editBoxAccount = editBox;
    accountInput:getParent():addChild(editBox);
    accountInput:setVisible(false);
    local tipLabel = findChildByName(CT, "account_node/tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_TINY2, TextStyleM.TEXT_COLOR_GRAY, nil, nil, nil, nil, 23);
    tipLabel:setString(getLocStr("input_account_tip"));

    -- 输入密码
    local pwdInput = findChildByName(CT, "pwd_node/input_pwd");
    local editBoxSize = pwdInput:getContentSize();
    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setAnchorPoint(cc.p(0, 0.5));
    editBox:setPosition(pwdInput:getPosition());
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder(getLocStr("input_password"));
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_GRAY2);
    editBox:setFontColor(TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    editBox:setMaxLength(MAX_PASSWORD_LEN);
    editBox:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD);
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);
    self.editBoxPwd = editBox;
    pwdInput:getParent():addChild(editBox);
    pwdInput:setVisible(false);
    local tipLabel = findChildByName(CT, "pwd_node/tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_TINY2, TextStyleM.TEXT_COLOR_GRAY, nil, nil, nil, nil, 23);
    tipLabel:setString(getLocStr("input_password_tip"));

    -- 再次输入密码
    local pwdInput2 = findChildByName(CT, "pwd_node2/input_pwd");
    local editBoxSize = pwdInput2:getContentSize();
    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setAnchorPoint(cc.p(0, 0.5));
    editBox:setPosition(pwdInput2:getPosition());
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder(getLocStr("input_password_again"));
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_GRAY2);
    editBox:setFontColor(TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    editBox:setMaxLength(MAX_PASSWORD_LEN);
    editBox:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD);
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);
    self.editBoxPwd2 = editBox;
    pwdInput2:getParent():addChild(editBox);
    pwdInput2:setVisible(false);
end

-- 注册按钮点击事件
function UIQCAccountRegister:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIQCAccountRegister");

            -- 显示上一级界面
            local uiChannelSelectQC = UIMgr.getCurrentScene():getFormByName("UIChannelSelectQC");
            uiChannelSelectQC:setVisible(true);
        end
    end
    AddTouchEventListener(btnBack, onBackClick);
    AddBackEventHandler(self, btnBack, btnBack.touchEventListener);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    btnBack:setOpacity(0);

    -- 返回图标
    local backImg = findChildByName(self.node, "CT/back");
    backImg:setTouchEnabled(true);
    backImg:addTouchEventListener(onBackClick);

    -- 注册按钮
    local btnReg = findChildByName(self.node, "CT/register");
    local function onRegisterClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:tryRegister();
        end
    end
    btnReg:addTouchEventListener(onRegisterClick);
    TextStyleM.setTextStyle(btnReg, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_WHITE, false);
    btnReg:setTitleText(getLocStr("btn_text_register"));

    -- 点击背景底图关闭
    local bgImg = findChildByName(self.node, "bg/bgImg");
    bgImg:setTouchEnabled(true);
    bgImg:addTouchEventListener(onBackClick);
end

-- 尝试注册
function UIQCAccountRegister:tryRegister()
    local account   = removeTabAndSpace(self.editBoxAccount:getText());
    local password  = removeTabAndSpace(self.editBoxPwd:getText());
    local password2 = removeTabAndSpace(self.editBoxPwd2:getText());

    if string.len(account) == 0 then
        alert(getLocStr("account_cannot_be_null"));
        return;
    end

    if string.len(account) < MIN_ACCOUNT_LEN or
       string.len(account) > MAX_ACCOUNT_LEN then
        -- 账号长度不正确
        alert(getLocStr("account_length_error"));
        return;
    end

    account = string.gsub(account, "@", "#");

    -- 账号只能包含字母、数字、下划线
    -- 检查是否包含违禁字符
    local function isValidAccount()
        -- 仅包含字母、数字、下划线和空格
        local pattern = "[%w_%s]";
        local length = string.len(account);
        for i = 1, length do
            local ch = string.sub(account, i, i);
            if nil == string.match(ch, pattern) then
                return false;
            end
        end
        return true;
    end

    if not isValidAccount() then
        -- 账号不符合规则
        alert(getLocStr("account_not_conform_to_the_rules"));
        return false;
    end

    if string.len(password) == 0 then
        alert(getLocStr("password_cannot_be_null"));
        return;
    end

    if string.len(password) < MIN_PASSWORD_LEN or
       string.len(password) > MAX_PASSWORD_LEN  then
        -- 密码长度不合法
        alert(getLocStr("password_length_error"));
        return;
    end

    if password ~= password2 then
        -- 两次输入的密码不一致
        alert(getLocStr("passwords_not_match"));
        return;
    end

    -- 判断网络状态
    if (not NetworkStatus.isWifiConnected() and
        not NetworkStatus.isMobileConnected()) then
        alert(getLocStr("network_is_unavailable"));
        return;
    end

    -- 显示等待中
    showCommunicatingForm(getLocStr("waiting"), nil, nil, TIME_OUT_LIMIT);

    -- 注册
    AccountM.registerQCAccount(account, password);
end


